package com.tony.mywork.huju.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpSendUtil {
	private final static Logger logger = LoggerFactory.getLogger(HttpSendUtil.class);

	private final static int defaultReadTimeoutMS = 32000;
	
	private final static int defaultConnectTimeoutMS = 32000;
	
	
	public static String sendGet(String url, String params) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlName = "";
			if (params == null || params.trim().isEmpty()) {
				urlName = url;
			} else {
				urlName = url + "?" + params;
			}

			URL realUrl = new URL(urlName);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setConnectTimeout(defaultConnectTimeoutMS);
			conn.setReadTimeout(defaultReadTimeoutMS);
			conn.connect();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(ExceptionUtils.getStackTrace(e));
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
				logger.error(ExceptionUtils.getStackTrace(ex));
			}
		}
		return result;
	}

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @param timeout
	 *            连接超时时间
	 * @return URL所代表远程资源的响应
	 * @throws Exception
	 */
	public static String sendPost(String url, String params, int timeout, String contentType)
			throws Exception {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();

			if (timeout >= 0) {
				conn.setConnectTimeout(timeout);
			} else {
				conn.setConnectTimeout(defaultConnectTimeoutMS);
				conn.setReadTimeout(defaultReadTimeoutMS);
			}
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			if (contentType != null && !"".equals(contentType)) {
				conn.setRequestProperty("Content-Type", contentType);
			} else {
				conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			}
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
			out.print(params);
			// System.out.println(params);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(ExceptionUtils.getStackTrace(e));
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				logger.error(ExceptionUtils.getStackTrace(ex));
			}
		}
		return result;
	}

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，Map<String, Object>形式。
	 * @return URL所代表远程资源的响应
	 * @throws Exception
	 */
	// public static String sendPost(String url, Map<String, Object> params)
	// throws Exception {
	// String result = "";
	//
	// String encodedParams = URLBuilder.httpBuildQuery(params, null);
	// result = sendPost(url, encodedParams);
	// return result;
	// }

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。 不设置连接超时
	 * @return URL所代表远程资源的响应
	 * @throws Exception
	 */
	public static String sendPost(String url, String params) throws Exception {
		String result = "";

		result = sendPost(url, params, -1, null);
		return result;
	}

	public static String sendJsonPost(String platformUrl, String msg) {

		try {
			// 创建连接
			URL url = new URL(platformUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);

			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
			connection.setConnectTimeout(defaultConnectTimeoutMS);
			connection.setReadTimeout(defaultReadTimeoutMS);
			connection.connect();

			// POST请求
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.writeBytes(msg);
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			// 断开连接
			connection.disconnect();
			return sb.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("MalformedURLException exception");
			logger.error(ExceptionUtils.getFullStackTrace(e));
			return "";
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("UnsupportedEncodingException");
			logger.error(ExceptionUtils.getFullStackTrace(e));
			return "";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("UnsupportedEncodingException");
			logger.error(ExceptionUtils.getFullStackTrace(e));
			return "";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Exception");
			logger.error(ExceptionUtils.getFullStackTrace(e));
			return "";
		}

	}

	public static void main(String[] args) throws Exception {
		String postData = "{\"backtime\":\"00000000\",\"cycle\":\"12\",\"mobile\":\"18648377770\",\"version\":\"9.3.0\"}";

		String ret = sendJsonPost("http://172.16.4.51:80/ParseSmsServer/rest/report/", postData);

		System.out.println("ret:" + ret);
	}
}
